package panda.android.notebook.dialog;

import java.io.File;
import java.io.IOException;

import android.app.Dialog;
import android.content.Context;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class LuyinDialog extends BaseDialog {

	public interface sendPath {
		public void Path(String path);
	}

	private Context mContext;
	sendPath p;

	public sendPath getP() {
		return p;
	}

	public void setP(sendPath p) {
		this.p = p;
	}

	public LuyinDialog(Context context, int theme) {
		super(context, theme);
		// TODO Auto-generated constructor stub
		mContext = context;
	}

	private boolean isStart = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		

		TextView textView = new TextView(mContext);
		textView.setText("初始化完成！");
		textView.setId(2);
		layout.addView(textView, new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));

		Button button = new Button(mContext);
		button.setText("开始录音");
		button.setId(1);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isStart)
					start();
				else {
					stop();
					dismiss();
				}
			}
		});
		layout.addView(button, new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		
		title.setText("录音");
	}

	MediaRecorder mRecorder;
	String path;

	public void start() {

		mRecorder = new MediaRecorder();
		// 设置音源为Micphone
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		// 设置封装格式
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/note/amr");
		file.mkdirs();
		path = file.toString() + "/" + System.currentTimeMillis() + ".amr";
		mRecorder.setOutputFile(path);
		// 设置编码格式
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		((Button) findViewById(1)).setText("停止录音");
		((TextView) findViewById(2)).setText("正在录音！");
		try {
			mRecorder.prepare();
		} catch (IOException e) {

		}

		mRecorder.start();
		isStart = true;
	}

	public void stop() {
		mRecorder.stop();
		mRecorder.release();
		mRecorder = null;
		((Button) findViewById(1)).setText("开始录音");
		((TextView) findViewById(2)).setText("初始化完成！");
		p.Path(path);
		isStart = false;
	}

	@Override
	public void dismiss() {
		// TODO Auto-generated method stub
		if (mRecorder != null) {
			stop();
		}
		super.dismiss();
	}

}
